package com.dpiinc.TechPage;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.dpiinc.TechPage.activity.BottomBarActivity;
import com.dpiinc.TechPage.api.BaseObserver;
import com.dpiinc.TechPage.api.RetrofitFactory;
import com.dpiinc.TechPage.api.RxSchedulers;
import com.dpiinc.TechPage.model.BaseEntity;
import com.dpiinc.TechPage.model.jbean.AuthenticateInfo;
import com.dpiinc.TechPage.room.RoomAiWriterDatabase;
import com.dpiinc.TechPage.room.bean.UserEntity;
import com.dpiinc.TechPage.user.CommonWebviewActivity;
import com.dpiinc.TechPage.user.PhoneInputActivity;
import com.dpiinc.TechPage.user.logic.NoteLabelLogic;
import com.dpiinc.TechPage.user.utils.Constant;
import com.dpiinc.TechPage.user.utils.ToastUtils;
import com.dpiinc.TechPage.widget.LoadingView;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginBehavior;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;

import com.google.android.gms.tasks.OnCompleteListener;

import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.mob.tools.utils.UIHandler;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.utils.WechatClientNotExistException;
import io.reactivex.Observable;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by hu489_000 on 2018-06-24
 *
 * 登录界面
 */
public class LoginActivity extends AppCompatActivity implements android.os.Handler.Callback, PlatformActionListener {
    private static final String TAG = "LoginActivity";

    private static final int MSG_LOGIN = 2;
    private static final int MSG_AUTH_CANCEL = 3;
    private static final int MSG_AUTH_ERROR = 4;
    private static final int MSG_AUTH_COMPLETE = 5;
    // private final String clientId = "988771466677-i1uhfashn8mo04l9i8onamibkbeh42tj.apps.googleusercontent.com";
    //更换google API clientId，上面的是旧的
    private final String clientId = "289287932123-39nnled152sn1abcbh1g5p47k5cah1q2.apps.googleusercontent.com";

    private int login_state = 1;

    Button btn_login_tel;
    Button btn_login_wechat;
    Button btn_login_google;
    LoginButton btn_login_facebook;

    private ImageView tv_user_agreement_iv;
    private boolean isUserAgreementOK;

    UserEntity userWeChat = new UserEntity();
    private Boolean isReady = false;
    private Boolean isPhone = true;
    private static final int RC_SIGN_IN = 9001;
    private FirebaseAuth mAuth;
    private GoogleSignInClient mGoogleSignInClient;
    private CallbackManager callbackManager;
    private TextView tvUserAgreement;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        super.onCreate(savedInstanceState);
        //  setstatusBarColor(R.color.color_00263C);
        //哈哈
        //透明状态栏
        int sdk = Build.VERSION.SDK_INT;
        if (sdk >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            //透明状态栏
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

            if (sdk >= Build.VERSION_CODES.N) {
                try {
                    @SuppressLint("PrivateApi") Class<?> decorViewCls = Class.forName("com.android.internal.policy.DecorView");
                    Field statusBarColorField = decorViewCls.getDeclaredField("mSemiTransparentStatusBarColor");
                    statusBarColorField.setAccessible(true);
                    statusBarColorField.setInt(getWindow().getDecorView(), Color.TRANSPARENT);
                } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

        setContentView(R.layout.login_main);

        initGoogleLogin();
        initFacebookLogin();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               isReady = true;
                               if (!isPhone) {
                                   LoadingView.dismissLoadingView();
                                   startActivity(new Intent(LoginActivity.this, PhoneInputActivity.class));
                               }
                           }
                       },
                1500);
        initUserAgreement();
        btn_login_tel = findViewById(R.id.btn_login_tel);
        btn_login_tel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isUserAgreementOK) {
                    goAnim();
                    return;
                }
                if (isReady) {
                    isPhone = true;
                    startActivity(new Intent(LoginActivity.this, PhoneInputActivity.class));
                } else {
                    isPhone = false;
                    LoadingView.createLoadingViewAndShow(LoginActivity.this, 0, "");
                }
//                添加测试账号
//                userAuthenticate(LoginActivity.this, "15206283969", "123456");
            }
        });
        btn_login_wechat = findViewById(R.id.btn_login_wechat);
        btn_login_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isUserAgreementOK) {
                    goAnim();
                    return;
                }
                authorize(new Wechat());
            }
        });

        btn_login_google = findViewById(R.id.btn_login_google);
        btn_login_google.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isUserAgreementOK) {
                    signIn();
                } else {
                    goAnim();
                }
            }
        });

        tv_user_agreement_iv = findViewById(R.id.tv_user_agreement_iv);
        findViewById(R.id.tv_user_agreement_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isUserAgreementOK = !isUserAgreementOK;
                tv_user_agreement_iv.setImageResource(isUserAgreementOK ? R.mipmap.ic_eraser_selecter_small : R.mipmap.ic_eraser_unselecter_small);
            }
        });

        btn_login_facebook = findViewById(R.id.btn_login_facebook);
        btn_login_facebook.setReadPermissions(Arrays.asList("email"));
        btn_login_facebook.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Log.i(TAG, "facebook onSuccess: " + loginResult.toString());
                AccessToken token = loginResult.getAccessToken();
                RoomAiWriterDatabase db = RoomAiWriterDatabase.getInstance(LoginActivity.this);
                UserEntity user = new UserEntity();
                user.setUid(token.getUserId());
                user.setAccessToken(token.getToken());
                user.setExpireTime("");
                user.setRefreshToken("");
                user.setPhoneNum("");
                db.userDao().clearTable();
                db.userDao().insert(user);
                startMain();
                NoteLabelLogic.getNoteLabel(LoginActivity.this, null);
            }

            @Override
            public void onCancel() {
                Log.i(TAG, "facebook onCancel: ");
            }

            @Override
            public void onError(FacebookException error) {
                Log.i(TAG, "facebook onError: " + error.toString());
            }
        });
        btn_login_facebook.setClickable(false);
        findViewById(R.id.btn_login_facebook_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isUserAgreementOK) {
                    LoginManager.getInstance().setLoginBehavior(LoginBehavior.NATIVE_WITH_FALLBACK);
                    LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("public_profile", "email"));
//                    LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("public_profile"));
                } else {
                    btn_login_facebook.setClickable(false);
                    goAnim();
                }
            }
        });
        btn_login_facebook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });


//        try {
//            PackageInfo info = getPackageManager().getPackageInfo(
//                    "com.dpiinc.TechPage",
//                    PackageManager.GET_SIGNATURES);
//            for (Signature signature : info.signatures) {
//                MessageDigest md = MessageDigest.getInstance("SHA");
//                md.update(signature.toByteArray());
//                Log.i("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));//
//            }
//
//            //CA:3A:1C:93:6F:F3:53:81:AF:D0:C6:05:F2:AD:E8:43:BD:DC:C1:71
//            byte[] cert = info.signatures[0].toByteArray();
//            MessageDigest md = MessageDigest.getInstance("SHA1");
//            byte[] publicKey = md.digest(cert);
//            StringBuffer hexString = new StringBuffer();
//            for (int i = 0; i < publicKey.length; i++) {
//                String appendString = Integer.toHexString(0xFF & publicKey[i])
//                        .toUpperCase(Locale.US);
//                if (appendString.length() == 1)
//                    hexString.append("0");
//                hexString.append(appendString);
//                hexString.append(":");
//            }
//            String result = hexString.toString();
//            Log.i("KeyHash SHA1 :", result.substring(0, result.length() - 1));//SHA1
//
//        } catch (PackageManager.NameNotFoundException e) {
//
//        } catch (NoSuchAlgorithmException e) {
//
//        }

       // setPermissionXX(this);
    }

    public static void setPermissionXX(Context context) {
        XXPermissions.with(context)
                // 申请单个权限
                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                // 申请多个权限
                // .permission(Permission.Group.STORAGE)
                // 设置权限请求拦截器（局部设置）
                //.interceptor(new PermissionInterceptor())
                // 设置不触发错误检测机制（局部设置）
                //.unchecked()
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (!allGranted) {
                            Log.e("TAG", "获取部分权限成功，但部分权限未正常授予");
                            //toast("获取部分权限成功，但部分权限未正常授予");
                            return;
                        }
                        Log.e("TAG", "获取录音和日历权限成功");
                        //toast("获取录音和日历权限成功");
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        if (doNotAskAgain) {
                            Log.e("TAG", "被永久拒绝授权，请手动授予录音和日历权限");
                            //toast("被永久拒绝授权，请手动授予录音和日历权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(context, permissions);
                        } else {
                            Log.e("TAG", "获取录音和日历权限失败");
                            //toast("获取录音和日历权限失败");
                        }
                    }
                });
    }

    public void goAnim() {
        Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
        findViewById(R.id.tv_user_agreement_layout).startAnimation(shake);
    }


    private void initUserAgreement() {
        tvUserAgreement = findViewById(R.id.tv_user_agreement);
        TextView tv_user_agreement2 = findViewById(R.id.tv_user_agreement2);
        tvUserAgreement.setVisibility(View.VISIBLE);
        tv_user_agreement2.setVisibility(View.VISIBLE);
        tvUserAgreement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              //  if ("en".equals(getSharedPreferences("app_language", Context.MODE_PRIVATE).getString("lauType", Locale.getDefault().getLanguage()))) {
                    CommonWebviewActivity.webviewEntrance(LoginActivity.this, Constant.PROTOCOL_AGREEMENT, "Agreement");
               /* } else {
                    CommonWebviewActivity.webviewEntrance(LoginActivity.this, Constant.APP_AGREEMENT, "用户协议");
                }*/
            }
        });

        tv_user_agreement2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             //   if ("en".equals(getSharedPreferences("app_language", Context.MODE_PRIVATE).getString("lauType", Locale.getDefault().getLanguage()))) {
                    CommonWebviewActivity.webviewEntrance(LoginActivity.this, Constant.PROTOCOL_AGREEMENT, "Agreement");
             /*   } else {
                    CommonWebviewActivity.webviewEntrance(LoginActivity.this, Constant.APP_PROTOCOL, "隐私协议");
                }*/
            }
        });

    }

    public static String getStringDate(Date currentTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    private void initFacebookLogin() {
        callbackManager = CallbackManager.Factory.create();
    }

    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    private void initGoogleLogin() {
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(clientId)//default_web_client_id   server_client_id
                .requestEmail()
                .build();
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        // [START initialize_auth]
        // Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEventCode() == MessageEvent.EVENT_USER_VERIFICATION_OK) {
            userAuthenticate(LoginActivity.this, (String) event.getOject(), null);
        }
        /* Do something */
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (login_state == 2) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (userWeChat.getUid() == null) {
                        LoadingView.dismissLoadingView();
                    }
                }
            }, 2000);
            login_state = 1;
        }
    }

    private void authorize(Platform plat) {
        if (plat.isAuthValid()) {
            plat.removeAccount(true);
        }
        plat.setPlatformActionListener(this);
        plat.SSOSetting(true);
        plat.showUser(null);
        login_state = 2;
        LoadingView.createLoadingViewAndShow(LoginActivity.this, R.style.CustomDialog, getString(R.string.logining_wait));
    }


    public void onComplete(Platform platform, int action,
                           HashMap<String, Object> res) {
        AWLog.e(TAG, "onComplete");
        if (action == Platform.ACTION_USER_INFOR) {
            UIHandler.sendEmptyMessage(MSG_AUTH_COMPLETE, LoginActivity.this);
            login(platform.getName(), platform.getDb().getUserId(), res);
        }
        userWeChat.setUid(System.currentTimeMillis() + "");
        userWeChat.setNickname((String) res.get("nickname"));
        userWeChat.setUnionid((String) res.get("unionid"));
        userWeChat.setOpenid((String) res.get("openid"));
        System.out.println(res);
        System.out.println("------nickname ---------" + res.get("nickname"));
        System.out.println("------unionid ---------" + res.get("unionid"));
        System.out.println("------openid ---------" + res.get("openid"));
        System.out.println("------headimgurl ---------" + res.get("headimgurl"));
        downloadImage((String) res.get("headimgurl"));

    }

    public void onError(Platform platform, int action, Throwable t) {
        if (t instanceof WechatClientNotExistException) {
            UIHandler.sendEmptyMessage(MSG_AUTH_ERROR, this);
        }
        t.printStackTrace();

    }

    public void onCancel(Platform platform, int action) {
        if (action == Platform.ACTION_USER_INFOR) {
            UIHandler.sendEmptyMessage(MSG_AUTH_CANCEL, this);
        }
    }

    private void login(String plat, String userId, HashMap<String, Object> userInfo) {
        System.out.println("-------private void login--------");
        Message msg = new Message();
        msg.what = MSG_LOGIN;
        msg.obj = plat;
        UIHandler.sendMessage(msg, this);
    }

    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_LOGIN: {

//                Toast.makeText(this, "logining", Toast.LENGTH_SHORT).show();
                System.out.println("-------logining--------");

//				Builder builder = new Builder(this);
//				builder.setTitle(R.string.if_register_needed);
//				builder.setMessage(R.string.after_auth);
//				builder.setPositiveButton(R.string.ok, null);
//				builder.create().show();
            }
            break;
            case MSG_AUTH_CANCEL: {
                System.out.println("-------MSG_AUTH_CANCEL--------");
            }
            break;
            case MSG_AUTH_ERROR: {

                ToastUtils.showTopTip(this, getString(R.string.WechatClientNotExistException));
                System.out.println("-------MSG_AUTH_ERROR--------");
            }
            break;
            case MSG_AUTH_COMPLETE: {
                System.out.println("--------MSG_AUTH_COMPLETE-------");
            }
            break;
        }
        return false;
    }


    private void downloadImage(String url) {
        AWLog.e(TAG, "start downloadImage");
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //将响应数据转化为输入流数据
                InputStream inputStream = response.body().byteStream();
                //将输入流数据转化为Bitmap位图数据
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                //第一步:将Bitmap压缩至字节数组输出流ByteArrayOutputStream
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
                //第二步:利用Base64将字节数组输出流中的数据转换成字符串String
                byte[] byteArray = byteArrayOutputStream.toByteArray();
                String imageString = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
                userWeChat.setNickImage(imageString);

                AWLog.e(TAG, "finish downloadImage");
                thirdUserAuthenticate(LoginActivity.this, userWeChat.getOpenid(), userWeChat.getUnionid());
//                RoomAiWriterDatabase db = RoomAiWriterDatabase.getInstance(LoginActivity.this);
//                db.userDao().clearTable();
//                Log.d(TAG,"userWeChat = " + userWeChat);
//                db.userDao().insert(userWeChat);
//                startMain();
            }
        });

    }

    private void startMain() {
        Intent intent = new Intent(LoginActivity.this, BottomBarActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }


    /**
     * 自有用户登陆
     *
     * @param context
     * @param telPhone
     * @param password
     */
    private void userAuthenticate(Context context, String telPhone, String password) {
        LoadingView.createLoadingViewAndShow(LoginActivity.this, R.style.CustomDialog, context.getString(R.string.logining_wait));
        String platformInfo = "Android-" + getDeviceBrand() + "-" + getSystemModel() + "-" + getSystemVersion() + "-" + getVersionName(this);
        String language = getSharedPreferences("app_language", Context.MODE_PRIVATE).getString("lauType", Locale.getDefault().getLanguage());
        Observable<BaseEntity<AuthenticateInfo>> observable = RetrofitFactory.getInstance().userAuthenticate("111", telPhone, password, platformInfo, language);
        final String tel = telPhone;
        BaseObserver mBaseObserver = new BaseObserver<AuthenticateInfo>(context) {
            @Override
            protected void onHandleError(int code) {
                super.onHandleError(code);
                Log.d(TAG, "onHandleError code = " + code);
            }

            @Override
            protected void onHandleSuccess(AuthenticateInfo userInfo) {
                // 保存用户信息等操作
                Log.d(TAG, "onHandleSuccess userInfo = " + userInfo);
                RoomAiWriterDatabase db = RoomAiWriterDatabase.getInstance(LoginActivity.this);
                UserEntity user = new UserEntity();
                user.setUid(userInfo.getuId());
                user.setAccessToken(userInfo.getAccessToken());
                user.setExpireTime(userInfo.getExpireTime());
                user.setRefreshToken(userInfo.getRefreshToken());
                user.setPhoneNum(tel);
                db.userDao().clearTable();
                db.userDao().insert(user);

                AIWriteApplication.instance.getOssConfig();//这个时候重新保存下需要上传的oss数据

                startMain();
                NoteLabelLogic.getNoteLabel(LoginActivity.this, null);
            }
        };
        observable.compose(RxSchedulers.compose()).subscribe(mBaseObserver);
    }

    /**
     * 自有用户登陆
     *
     * @param context
     * @param unionid
     */
    private void thirdUserAuthenticate(Context context, String openid, String unionid) {
        AWLog.e(TAG, "start thirdUserAuthenticate");
        String platformInfo = "Android-" + getDeviceBrand() + "-" + getSystemModel() + "-" + getSystemVersion() + "-" + getVersionName(this);
//        LoadingView.createLoadingViewAndShow(LoginActivity.this, R.style.CustomDialog, "正在登录，请稍后");
        String language = getSharedPreferences("app_language", Context.MODE_PRIVATE).getString("lauType", Locale.getDefault().getLanguage());
        Observable<BaseEntity<AuthenticateInfo>> observable = RetrofitFactory.getInstance().userThirdAuthenticate("1000000000", "1", openid, unionid, platformInfo, language);
//        Observable<BaseEntity<AuthenticateInfo>> observable = RetrofitFactory.getInstance().userThirdAuthenticate("1000000000", "1", unionid);

        BaseObserver mBaseObserver = new BaseObserver<AuthenticateInfo>(context) {
            @Override
            protected void onHandleError(int code) {
                super.onHandleError(code);
                Log.d(TAG, "onHandleError code = " + code);
            }

            @Override
            protected void onHandleSuccess(AuthenticateInfo userInfo) {
                // 保存用户信息等操作
                Log.d(TAG, "onHandleSuccess userInfo = " + userInfo);

                RoomAiWriterDatabase db = RoomAiWriterDatabase.getInstance(LoginActivity.this);
                UserEntity user = new UserEntity();
                user.setUid(userInfo.getuId());
                user.setAccessToken(userInfo.getAccessToken());
                user.setExpireTime(userInfo.getExpireTime());
                user.setRefreshToken(userInfo.getRefreshToken());
                user.setNickImage(userWeChat.getNickImage());
                user.setUnionid(userWeChat.getUnionid());
                user.setNickname(userWeChat.getNickname());
                user.setOpenid(userWeChat.getOpenid());
                db.userDao().clearTable();
                db.userDao().insert(user);
                startMain();
                NoteLabelLogic.getNoteLabel(LoginActivity.this, null);
            }
        };
        observable.compose(RxSchedulers.compose()).subscribe(mBaseObserver);
    }

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return 系统版本号
     */
    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }


    //版本名
    public static String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;
        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pi;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //facebook登录
        callbackManager.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RC_SIGN_IN:
                Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
                try {
                    // Google Sign In was successful, authenticate with Firebase
                    GoogleSignInAccount account = task.getResult(ApiException.class);
                    RoomAiWriterDatabase db = RoomAiWriterDatabase.getInstance(LoginActivity.this);
                    UserEntity user = new UserEntity();
                    user.setUid(account.getId());
                    user.setAccessToken(account.getIdToken());
                    user.setExpireTime("0");
                    user.setRefreshToken(account.getIdToken());
                    user.setPhoneNum("");
                    db.userDao().clearTable();
                    db.userDao().insert(user);
                  //  startMain();
                    NoteLabelLogic.getNoteLabel(LoginActivity.this, null);
                    Log.d(TAG, "firebaseAuthWithGoogle:" + account.getAccount().toString());
                    thirdUserAuthenticate(LoginActivity.this,account.getId(), account.getIdToken());
                 /*   onComplete(Platform platform, int action,
                    HashMap<String, Object> res) */
                    firebaseAuthWithGoogle(account.getIdToken());
                } catch (ApiException e) {
                    // Google Sign In failed, update UI appropriately
                    Log.w(TAG, "Google sign in failed", e);
                    // [END_EXCLUDE]
                }
                break;
        }
    }

    private void firebaseAuthWithGoogle(String idToken) {
        // [END_EXCLUDE]
        AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                            Log.i(TAG, "onComplete: " + user);
                        } else {
                            Log.i(TAG, "onComplete: fails" +task.toString());
                            // If sign in fails, display a message to the user.
                        }
                    }
                });
    }
}
